package zld369504.tw.m_team.fragments;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import zld369504.tw.m_team.OnRecyclerViewItemClickListener;
import zld369504.tw.m_team.R;
import zld369504.tw.m_team.ShowImageActivity;
import zld369504.tw.m_team.dao.TorrentDetail;


public class TorrentDMMFragment extends Fragment implements View.OnClickListener, OnRecyclerViewItemClickListener {

    public static final String TAG = "TorrentDMMFragment";

    private View rootView;
    private ImageView ivSmallCover;
    private TableLayout dmmTableLayout;
    private TextView tvDmmDetailInfo;
    private RecyclerView dmmScreenshotRecyclerView;
    private RecyclerViewAdapter adapter;

    private TorrentDetail.DMMInfo dmmInfo;

    public static TorrentDMMFragment getInstance(TorrentDetail.DMMInfo dmmInfo) {
        TorrentDMMFragment fragment = new TorrentDMMFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("dmmInfo", dmmInfo);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            dmmInfo = (TorrentDetail.DMMInfo) bundle.getSerializable("dmmInfo");
        }
        adapter = new RecyclerViewAdapter();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_dmm, container, false);
        ivSmallCover = rootView.findViewById(R.id.ivSmallCover);
        dmmTableLayout = rootView.findViewById(R.id.dmmTableLayout);
        tvDmmDetailInfo = rootView.findViewById(R.id.tvDmmDetailInfo);
        dmmScreenshotRecyclerView = rootView.findViewById(R.id.dmmScreenshotRecyclerView);
        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dynamicLoadCoverImage();
        dynamicLoadTableData();
        tvDmmDetailInfo.setText(dmmInfo.getText());
        adapter.setDataSource(dmmInfo.getScreenshotPicUrlList());
        adapter.setOnItemClickListener(this);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        dmmScreenshotRecyclerView.setLayoutManager(layoutManager);
        dmmScreenshotRecyclerView.addItemDecoration(new SpacesItemDecoration(32));
        dmmScreenshotRecyclerView.setNestedScrollingEnabled(false);
        dmmScreenshotRecyclerView.setAdapter(adapter);
    }

    private void dynamicLoadCoverImage() {
        Picasso.with(getActivity())
                .load(dmmInfo.getCoverLargeImageUrl())
                .transform(getTransformation(ivSmallCover))
                .into(ivSmallCover);
        ivSmallCover.setOnClickListener(this);
    }

    private void dynamicLoadTableData() {
        LinkedHashMap<String, String> map = dmmInfo.getBriefInfo();
        for (Map.Entry<String, String> element : map.entrySet()) {
            String strKey = element.getKey();
            String strObj = element.getValue();
            TableRow tableRow = new TableRow(getActivity());
            TextView textViewKey = new TextView(getActivity());
            textViewKey.setText(strKey);
            TextView textViewValue = new TextView(getActivity());
            textViewValue.setText(strObj);
            tableRow.addView(textViewKey);
            tableRow.addView(textViewValue);
            dmmTableLayout.addView(tableRow);
        }
    }

    private static Transformation getTransformation(final ImageView view) {
        return new Transformation() {
            @Override
            public Bitmap transform(Bitmap source) {
                int targetWidth = view.getWidth();

                //返回原图
                if (source.getWidth() == 0 || source.getWidth() < targetWidth) {
                    return source;
                }

                //如果图片大小大于等于设置的宽度，则按照设置的宽度比例来缩放
                double aspectRatio = (double) source.getHeight() / (double) source.getWidth();
                int targetHeight = (int) (targetWidth * aspectRatio);
                if (targetHeight == 0 || targetWidth == 0) {
                    return source;
                }
                Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
                if (result != source) {
                    // Same bitmap is returned if sizes are the same
                    source.recycle();
                }
                return result;
            }

            @Override
            public String key() {
                return "transformation" + " desiredWidth";
            }
        };
    }

    @Override
    public void onClick(View v) {
        if (v == ivSmallCover) {
            if (getActivity() != null) {
                Intent intent = new Intent(getActivity(), ShowImageActivity.class);
                intent.putExtra("URL", dmmInfo.getCoverLargeImageUrl());
                getActivity().startActivity(intent);
            }
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        LinkedHashMap<String, String> map = dmmInfo.getScreenshotPicUrlList().get(position);
        if (getActivity() != null) {
            Intent intent = new Intent(getActivity(), ShowImageActivity.class);
            intent.putExtra("URL", map.get("large"));
            getActivity().startActivity(intent);
        }
    }

    private class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

        private List<LinkedHashMap<String, String>> screenshotPicUrlList;
        private OnRecyclerViewItemClickListener l;

        public void setOnItemClickListener(OnRecyclerViewItemClickListener l) {
            this.l = l;
        }

        public void setDataSource(List<LinkedHashMap<String, String>> screenshotPicUrlList) {
            if (screenshotPicUrlList == null) {
                this.screenshotPicUrlList = new ArrayList<>();
            } else {
                this.screenshotPicUrlList = screenshotPicUrlList;
            }
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pic_screenshot, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            LinkedHashMap<String, String> map = screenshotPicUrlList.get(position);
            Picasso.with(getActivity())
                    .load(map.get("small"))
//                    .transform(getTransformation(holder.imageView))
                    .into(holder.imageView);
        }

        @Override
        public int getItemCount() {
            return screenshotPicUrlList.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

            ImageView imageView;

            public MyViewHolder(View itemView) {
                super(itemView);
                itemView.setOnClickListener(this);
                imageView = itemView.findViewById(R.id.imageView);
            }

            @Override
            public void onClick(View v) {
                if (l != null) {
                    l.onItemClick(v, getPosition());
                }
            }
        }
    }

    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.bottom = space;
            outRect.left = space;
            outRect.right = space;
            outRect.top = space;
        }
    }

}
